package org.android.bbox.activities;

import org.android.bbox.AbstractActivity;
import org.android.bbox.R;
import org.android.bbox.data.NoDatabaseException;
import org.android.bbox.data.Profil;
import org.android.bbox.utils.RId;

import android.database.Cursor;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class ProfilChoice extends AbstractActivity implements OnItemClickListener
{
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		this.chooseAProfil();
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id)
	{
		Toast msg = Toast.makeText(this, "Vous avez cliqué sur : " + id + "(" + position + ")", Toast.LENGTH_SHORT);
		msg.setGravity(Gravity.CENTER, msg.getXOffset() / 2, msg.getYOffset() / 2);
		msg.show();
	}

	private void addNewProfil()
	{
		this.setContentView(R.layout.profils_edit);
		Button btn = (Button) findViewById(R.id.profil_save);
		btn.setText(R.string.label_btn_add);
		btn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v)
			{
				ProfilChoice.this.saveProfil(true);
			}
		});
	}

	private void saveProfil(boolean isNew)
	{
		try
		{
			Profil.create(this,
				RId.getTextViewValue(this, R.id.profil_ip),
				RId.getTextViewValue(this, R.id.profil_name),
				RId.getTextViewValue(this, R.id.profil_login),
				RId.getTextViewValue(this, R.id.profil_password),
				RId.getTextViewValue(this, R.id.profil_password_user),
				RId.getCheckBoxValue(this, R.id.profil_save_password),
				RId.getTextViewValue(this, R.id.profil_image),
				RId.getTextViewValue(this, R.id.profil_color));
		}
		catch (NoDatabaseException e)
		{
		 	android.util.Log.e(this.getClass().toString(), e.getMessage(), e);
		}
	 	finish();
	}

	private void chooseAProfil()
	{
		this.setContentView(R.layout.profils_list);

		Cursor c = Profil.getAll(this);

		if (c.getCount() > 0)
		{
			ListView myList = (ListView) findViewById(android.R.id.list);
			myList.setOnItemClickListener(this);
			SimpleCursorAdapter sCAdapter = new SimpleCursorAdapter(this, R.layout.profils_list, c,
					new String[] { "name" }, new int[] { android.R.id.text1 });
			myList.setAdapter(sCAdapter);
		}
		else
		{
			this.addNewProfil();
		}
	}
}
